﻿namespace EAL.Database
{
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using EAL.Models;

    public class SaveChangesEventArgs
    {
        public SaveChangesEventArgs(DbChangeTracker tracker)
	    {
            Tracker = tracker;
	    }

        public readonly DbChangeTracker Tracker;
    }

    public class DbContext : System.Data.Entity.DbContext
    {
        public delegate void SaveChangesEventHandler(object sender, SaveChangesEventArgs e);
        public event SaveChangesEventHandler PreviewOnSaveChangesEvent;


        public DbContext()
            : base()            
        {
            this.Configuration.LazyLoadingEnabled = true;
            this.Configuration.AutoDetectChangesEnabled = true;
        }

        public DbSet<Options> Options { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<Address> Adresses { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<Customer> Customers { get; set; }
        public DbSet<Position> Positions { get; set; }

        public override int SaveChanges()
        {
            PreviewOnSaveChanges(new SaveChangesEventArgs(this.ChangeTracker));

            return base.SaveChanges();
        }


        protected void PreviewOnSaveChanges(SaveChangesEventArgs e)
        {
            var handler = PreviewOnSaveChangesEvent;

            if (handler != null)
            {
                handler(this, e);
            }
        }
    }
}
